namespace taurus.client {

    /**
     * IOHandler
     */
    export class IOHandler {
        private static ACTION_ID: string = "a";
        private static PARAM_ID: string = "p";

        private _engine: SocketEngine;

        public constructor(engine: SocketEngine) {
            this._engine = engine;
        }

        public onDataRead(data: ByteArray) {
            var compressed = data.readByte() > 0;
            var bytes = data.readBytes();
            if(compressed){
                bytes.uncompress();
            }
            var requestObject = TObject.newFromBinaryData(bytes);
            var packet = new Packet();
            if (requestObject.isNull(IOHandler.ACTION_ID)) {
                throw "Request rejected: No Action ID in request!";
            }
            packet.actionID = requestObject.getByte(IOHandler.ACTION_ID);
            packet.parameters = requestObject.getTObject(IOHandler.PARAM_ID);
            this._engine._controller.handlePacket(packet);
        }

        public onDataWrite(packet: Packet) {
            var obj2 = TObject.newInstance();
            obj2.putByte(IOHandler.ACTION_ID, packet.actionID);
            obj2.putTObject(IOHandler.PARAM_ID, packet.parameters);
            var array2 = obj2.toBinary();
            var compression = array2.length > this._engine.getProtocolCompression();
            if (compression) {
                array2.compress();
            }
            var binData = new ByteArray();
            binData.writeByte((compression ? 1 : 0));
            binData.writeBytes(array2.bytes);

            if (this._engine._socket.readyState == WebSocket.OPEN) {
                this._engine._socket.send(binData.bytes);
            }
        }
    }
}